package com.alks.function.service.impl;

import com.alks.common.utils.beanutils.StringUtils;
import com.alks.function.data.request.EmailSendRequest;
import com.alks.function.service.IEmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Value;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

@Slf4j
@Service
public class EmailServiceImpl implements IEmailService {

    @Value("${mail.config.smtpHost}")
    private String smtpHost;

    @Value("${mail.config.smtpPort}")
    private String smtpPort;

    @Value("${mail.config.username}")
    private String username;

    @Value("${mail.config.password}")
    private String password;

    @Value("${mail.config.fromAddress}")
    private String fromAddress;

    @Override
    public void sendEmail(EmailSendRequest request) {
        checkParams(request);
        Properties props = new Properties();
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.port", smtpPort);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.ssl.enable", "true"); // 启用SSL
        props.put("mail.smtp.ssl.protocols", "TLSv1.2"); // 强制使用TLS 1.2
        props.put("mail.smtp.connectiontimeout", "5000"); // 连接超时5秒
        props.put("mail.smtp.timeout", "10000"); // IO超时10秒
        props.put("mail.smtp.writetimeout", "10000"); // 写超时10秒
        props.put("mail.smtp.ssl.checkserveridentity", "true"); // 验证服务器身份

        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(fromAddress));
            // 设置收件人
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(fromAddress));
            message.setSubject("来自 " + request.getUsername() + " 的邮件", "UTF-8");
            message.setText(
                    "姓名: " + request.getUsername() + "\n" +
                    "邮箱: " + request.getEmail() + "\n" +
                    "联系方式: " + request.getContactInfo() + "\n" +
                    "内容: " + request.getContent()
            );

            message.setHeader("X-Mailer", "JavaMail-Aliyun");
            message.setHeader("X-Priority", "1"); // 高优先级
            message.setHeader("X-Aliyun-DirectMail-Sending", "true");

            Transport.send(message);
            log.info("Email sent successfully!");
        } catch (MessagingException mex) {
            mex.printStackTrace();
            throw new RuntimeException("Error sending email: " + mex.getMessage());
        }
    }

    /**
     * 参数校验
     * @param request
     */
    private void checkParams(EmailSendRequest request) {
        if (StringUtils.isBlank(request.getEmail()) && StringUtils.isBlank(request.getContactInfo())) {
            throw new RuntimeException("One of the contact information is required.");
        }
        if (StringUtils.isBlank(request.getContent())) {
            throw new RuntimeException("Content cannot be empty.");
        }
    }
}